import { invoke } from "@tauri-apps/api/core";

let localAppRequestCommand = "local_app_request";

export function initialize(
  initialPath: string,
  localAppRequestCommandOverride?: string,
) {
  if (localAppRequestCommandOverride) {
    localAppRequestCommand = localAppRequestCommandOverride;
  }

  proxyFetch();
  // 只在 Tauri 环境中替换内容，避免在浏览器中造成白屏
  if (window.__TAURI__) {
    window.addEventListener("DOMContentLoaded", async () => {
      const response = await window.fetch(initialPath);
      document.documentElement.innerHTML = await response.text();
    });
  }
}

function proxyFetch() {
  const originalFetch = window.fetch;

  window.fetch = async function (...args) {
    const [url, options] = args;
    if ((url as string).startsWith("ipc://") || !window.__TAURI__) {
      return originalFetch(...args);
    }

    const request = {
      uri: url,
      method: options?.method || "GET",
      headers: options?.headers || {},
      ...(options?.body && { body: options.body }),
    };
    let response: any = await invoke(localAppRequestCommand, {
      localRequest: request,
    });

    while ([301, 302, 303, 307, 308].includes(parseInt(response.status_code))) {
      const location = response.headers["location"];

      const redirectRequest = {
        uri: location,
        method: "GET",
        headers: {},
      };
      response = await invoke(localAppRequestCommand, {
        localRequest: redirectRequest,
      });
    }

    const bodyByteArray = new Uint8Array(response.body);
    const decoder = new TextDecoder("utf-8");
    const bodyText = decoder.decode(bodyByteArray);

    const status = parseInt(response.status_code);
    const headers = new Headers(response.headers);
    return new Response(bodyText, { status, headers });
  };
}
